package multidraw;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.Vector;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import multidraw.model.DrawingCanvasModel;
import multidraw.model.ModelObserver;
import multidraw.model.UserStatusObserver;
import multidraw.model.commands.AddUserCommand;
import multidraw.model.commands.ChangeColorCommand;
import multidraw.model.commands.ClearCanvasCommand;
import multidraw.model.commands.LeaveSessionCommand;
import multidraw.model.commands.SwitchingFillingCommand;
import multidraw.model.commands.WrapperCommand;



public class ControlPanelController implements ActionListener, ItemListener, ModelObserver {
	private DrawingCanvasModel myModel;
	private ControlPanelView myView;
	
	//private ClientListPanelView clientListPanel;
	
	protected boolean connectToggle = true; // true: "Connect" session, false: "Leave Session"
	
	protected boolean loginToggle = true; //true: "Login", "false" logout
	
	public ControlPanelController(DrawingCanvasModel model, ControlPanelView view) {
		this.myModel = model;
		this.myView = view;
		
	}

	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		if (e.getStateChange() == ItemEvent.SELECTED) {
			if (myModel.getSelectedObject() != null) {
				myModel.getSelectedObject().setPenColor(itemToColor(e.getItem()));
				//myModel.notifyObservers();
				ChangeColorCommand command = new ChangeColorCommand(myModel.getSelectedObject().getShapeID(),itemToColor(e.getItem()));
				//myModel.addCommand(command);
				try {
					WrapperCommand wrapCmd = new WrapperCommand(command);
					myModel.addCommand(wrapCmd);
				} catch (Exception e1) {
					System.out.println(e1);
				}
			} else {
		      myModel.setPenColor(itemToColor(e.getItem()));
			
			}			
		}
	}

	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub		

		if (e.getSource().equals(myView.getFillButton())) {
			SwitchingFillingCommand command = new SwitchingFillingCommand (myModel.getSelectedObject().getShapeID());
			//myModel.addCommand(command);
			try {
				WrapperCommand wrapCmd = new WrapperCommand(command);
				myModel.addCommand(wrapCmd);
			} catch (Exception e1) {
				System.out.println(e1);
			}
		
			//myModel.switchSelectedObjectFilling();
		}
		else if (e.getSource().equals(myView.getClearButton()))
			//myModel.clearCanvas();
		{
            ClearCanvasCommand command = new ClearCanvasCommand();
            //myModel.addCommand(command);
            try {
				WrapperCommand wrapCmd = new WrapperCommand(command);
				myModel.addCommand(wrapCmd);
			} catch (Exception e1) {
				System.out.println(e1);
			}
		}
		else if (e.getSource().equals(myView.getDrawingButton()))
		{
			myView.switchToDrawing();
		}
		else if (e.getSource().equals(myView.getConnectionsButton()))
		{
			myView.switchToConnection();
		}
		else if (e.getSource().equals(myView.getLoginButton())) {
			if (!myModel.getLoggedInStatus()) {
				// pop up a dialog box to get the username
				// have a method like "setUsername()" for the client.
				// i don't think we need any error checking for now.
				
				// within the method in ControlPanelView that this calls,
				// it should also enable the connectButton and the createButton
				// with the "setEnabled(true)" method of the JButton class
				
				
				String loginName = (String) JOptionPane.showInputDialog(myView, "Enter name:",
						"Log in", JOptionPane.PLAIN_MESSAGE, 
						((Icon) new ImageIcon("src/connection.jpg", "Login")), null, null); 
				
				// add logic to check the name first and see if it checks out
				// if it doesn't launch the error box that responds with the appropriate error
				//		-1 name is already in use
				//		-2 name doesn't exist
				
				// for now just should return 0 to work
				if (loginName != null && !loginName.equals("")) {
					myModel.setClientID(loginName);
					try {
						myModel.login();
					} catch (IOException ioe) {
						System.out.println(ioe);
						JOptionPane.showMessageDialog(null, ioe.getMessage());
						return;
					}
										
					
					//myModel.notifyObservers();
					myModel.notifyUserStatusObservers();										
				}			
			} else {
				logout();
			}
		}
		else if (e.getSource().equals(myView.getCreateButton())) {
			Object[] options = { "Yes, please", "No, thanks",
					"No eggs, no ham!" };
			int n = JOptionPane.showOptionDialog(null,
					"Would you like to share your current canvas?",
					"Share Session Options", JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE, null, null, null);
			// instantiate a new session.
			// OPTIONAL: transfer any existing data to the new session on the server.
				// will need additional logic for requesting a session name
				// unique names will need to be provided on a per user basis
			// set the client as the owner of the current session.
			if (n == JOptionPane.YES_OPTION){
				try {
					myModel.createSession(true);
					myModel.notifyUserStatusObservers();
				} catch (IOException ioe) {
					JOptionPane.showMessageDialog(null, ioe.getMessage());
				}
			} 
			else if (n == JOptionPane.NO_OPTION) {
				try {
					myModel.createSession(false);
					myModel.notifyUserStatusObservers();
				} catch (IOException ioe) {
					JOptionPane.showMessageDialog(null, ioe.getMessage());
				}
			}
			
		}
		else if (e.getSource().equals(myView.getConnectButton()))
		{
			if (myModel.getSessionID() == null) {
				// This part is not done yet, I was figuring out what the parameters to showInputDialog should be
				String ownerName = (String) JOptionPane.showInputDialog(myView, "Enter Owner name:",
						"Connect to Session", JOptionPane.PLAIN_MESSAGE, 
						((Icon) new ImageIcon("src/connection.jpg", "Connecting")), null, null); 
				
				// if owner name doesn't have a session, pop up an error window. i think there's a joptionpane for that.
				// otherwise, add the client's username and ClientID to the list of active users for that session
				if (ownerName != null && !ownerName.equals("")) {
					try {
						myModel.joinSession(ownerName);						
					} catch (IOException ioe) {
						System.out.println(ioe);
					}
								
				}
			} else {				
				//clean the local data
				myModel.leaveSession();				
			}
		}
		
	}

	protected Color itemToColor(Object item) {
	    if( item == null ) {
	      return myModel.getPenColor();
	    }
	    
	    if("black".equals(item)) {
	      return Color.black;
	    }
	    else if("blue".equals(item)) {
	      return Color.blue;
	    }
	    else if("green".equals(item)) {
	      return Color.green;
	    }
	    else if("red".equals(item)) {
	      return Color.red;
	    }
	    else {
	      return myModel.getPenColor();
	    }
	  }
	
	public void logout() {
		//drop from all the sessions		
		connectToggle = true;
		myView.getConnectButton().setText("Connect");
		//detach from server
		myModel.logout();
		myView.getLoginButton().setText("Login...");
		myView.getCreateButton().setEnabled(false);
		myView.getConnectButton().setEnabled(false);
		loginToggle = !loginToggle;
		
		myModel.notifyUserStatusObservers();
	}

	@Override
	public void updateContent() {
		// TODO Auto-generated method stub
		
	}
}
